package com.ibangnuo.framework.newLandpay.impl.common;

import com.alibaba.fastjson.JSONObject;
import com.ibangnuo.framework.newLandpay.impl.common.api.ResponseClientApi;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

/**
 * @Author: wwy
 * @Date: 2020-01-09 15:54
 */
public class ResponseClient implements ResponseClientApi {
    private String url1;

    public ResponseClient(String url1){
        this.url1 = url1;
    }
    public  String request(JSONObject object) {
        try {
            URL url = new URL(url1);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/json; charset=GBK");
            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());

            JSONObject paramsMap = object;

            out.write(paramsMap.toString().getBytes("GBK"));

            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"GBK"));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes());
                sb.append(lines);
            }
            String decode = URLDecoder.decode(sb.toString(), "UTF-8");
            reader.close();
            connection.disconnect();
            return decode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
